<?php

function newData($data = array()) {
	if(is_object($data)) {
		return $data;
	} else {
		return new data($data);
	}
}

class data {
	private $errors = array();
	private $children = array();
	private $value = null;
	private $validated = false;
	private $name = null;

	function __construct($data = array()) {
		if(is_array($data)) {
			foreach($data as $key => $child) {
				$this->addChild($child, $key);
			}
		} else {
			$this->value = $data;
		}
	}

	public function hasErrors() {
		if($this->errors==array()) {
			return false;
		} else {
			return true;
		}
	}

	public function setErrors($value) {
		return $this->errors;
	}

	public function getErrors() {
		return $this->errors;
	}

	public function addError($message) {
		$this->errors = arrayAppend($this->errors, array(
			$message
		));
	}

	public function hasChildren() {
		if($this->children==array()) {
			return false;
		} else {
			return true;
		}
	}

	public function addChild($child, $key = null) {
		if($key) {
			$this->children[$key] = newData($child);
			$this->children[$key]->setName($key);
		} else {
			$this->children = arrayAppend($this->children, array(
				newData($child)
			));
		}
	}

	public function deleteChild($child) {
		unset($this->children[$child]);
		return true;
	}

	public function listChildren() {
		return $this->children;
	}

	public function hasChild($name) {
		return isset($this->children[$name]);
	}

	public function setChild($name, $value) {
		$this->children[$name] = $value;
	}

	public function child($name) {
		return $this->children[$name];
	}

	public function getValue() {
		return $this->value;
	}

	public function setValue($value) {
		$this->value = $value;
	}

	public function validated() {
		return $this->validated;
	}

	public function setValidated($value) {
		$this->validated = $value;
	}

	public function setName($value) {
		$this->name = $value;
	}

	public function getName() {
		return $this->name;
	}

	public function toArray() {
		if($this->hasChildren()) {
			$return = array();
			$children = $this->listChildren();
			foreach($children as $name => $child) {
				$return[$name] = $child->toArray();
			}
			return $return;
		} else {
			return $this->getValue();
		}
	}
}

//EOF
